<template>
  <div class="chat-page">
    <div class="chat-container">
      <!-- 左侧应用列表 -->
      <div class="apps-sidebar">
        <div class="sidebar-header">
          <div class="sidebar-title">AI 助手</div>
          <div class="connection-status" :class="{ 'connected': connected }">
            {{ connected ? '已连接' : '未连接' }}
          </div>
        </div>
        <div class="apps-list">
          <div 
            v-for="app in aiApps" 
            :key="app.value" 
            class="app-item"
            :class="{ 'active': currentApp === app.value }"
            @click="selectApp(app.value)"
          >
            <div class="app-icon">
              <i :class="app.icon"></i>
            </div>
            <div class="app-name">{{ app.label }}</div>
          </div>
        </div>
        <!-- 添加模型选择器 -->
        <div class="model-selector">
          <div class="selector-title">模型选择</div>
          <el-select 
            v-model="agentModel" 
            placeholder="选择模型" 
            class="model-select"
            size="small"
          >
            <el-option
              v-for="model in modelOptions"
              :key="model.value"
              :label="model.label"
              :value="model.value"
            >
              <div class="model-option">
                <i class="el-icon-cpu"></i>
                <span>{{ model.label }}</span>
              </div>
            </el-option>
          </el-select>
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="content-area">
        <!-- 编剧助手表单对话框 -->
        <el-dialog
          v-model="scriptDialogVisible"
          title="AI 编剧助手"
          width="60%"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :show-close="false"
        >
          <el-form :model="scriptForm" label-width="100px">
            <el-form-item label="剧集类型">
              <el-select v-model="scriptForm.genre" placeholder="请选择剧集类型" class="genre-selector">
                <el-option
                  v-for="genre in genres"
                  :key="genre.value"
                  :label="genre.label"
                  :value="genre.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="剧情要点">
              <el-input
                v-model="scriptForm.plotPoints"
                type="textarea"
                :rows="4"
                placeholder="请输入主要剧情要点，每行一个要点"
              />
            </el-form-item>

            <el-form-item label="角色设定">
              <el-input
                v-model="scriptForm.characters"
                type="textarea"
                :rows="4"
                placeholder="请输入主要角色设定，每行一个角色"
              />
            </el-form-item>

            <el-form-item label="特殊要求">
              <el-input
                v-model="scriptForm.requirements"
                type="textarea"
                :rows="3"
                placeholder="请输入特殊要求，如风格、时长等"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="closeScriptDialog">取消</el-button>
              <el-button type="primary" @click="generateScript">生成剧本</el-button>
            </span>
          </template>
        </el-dialog>

        <!-- 聊天界面 -->
        <div v-if="currentApp" class="chat-content">
          <div class="chat-header">
            <div class="current-app-title">
              {{ aiApps.find(a => a.value === currentApp)?.label }}
            </div>
          </div>
          <div class="chat-body" ref="chatBody" @scroll="handleScroll">
            <div class="chat-messages">
              <template v-for="(message, index) in messages" :key="index">
                <div class="chat-message" :class="message.role" v-if="message.role !== 'reasoning'">
                  <div class="message-avatar">
                    {{ message.role === 'assistant' ? 'AI' : '我' }}
                  </div>
                  <div class="message-content" v-html="renderMessage(message)"></div>
                </div>
                <div v-if="message.role === 'reasoning'" class="reasoning-message">
                  <div class="reasoning-icon">
                    <i class="el-icon-cpu"></i>
                  </div>
                  <div class="reasoning-content" v-html="renderMarkdown(message.content)"></div>
                </div>
              </template>
            </div>
          </div>
          <div class="chat-input">
            <el-input
              v-model="inputText"
              type="textarea"
              :rows="3"
              :placeholder="currentAppPlaceholder"
              @keyup.enter.ctrl="handleSend"
              :disabled="!connected || loading"
            />
            <div class="chat-actions">
              <el-tooltip
                content="语音输入"
                placement="top"
                :show-after="500"
              >
                <el-button
                  type="primary"
                  :icon="isListening ? 'el-icon-microphone' : 'el-icon-microphone'"
                  :loading="isListening"
                  :class="{ 'is-listening': isListening }"
                  @click="isListening ? stopListening() : startListening()"
                  :disabled="!hasSpeechRecognition"
                >
                  {{ isListening ? '停止录音' : '语音输入' }}
                </el-button>
              </el-tooltip>
              <el-button
                type="primary"
                @click="handleSend"
                :loading="loading"
                :disabled="!connected || !inputText.trim()"
              >
                发送
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { createAgentAi } from "@/uses/agentAi.js";
import { ref, onMounted, nextTick, watch, computed, onUnmounted } from "vue";
import { ElMessage } from 'element-plus';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';

const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(str, { language: lang }).value;
      } catch (__) {}
    }
    return ''; // 使用默认的转义
  }
});

const aiApps = [
  { label: '通用对话', value: 'chat', icon: 'el-icon-chat-dot-round' },
  { label: '代码助手', value: 'code', icon: 'el-icon-monitor' },
  { label: '写作助手', value: 'writing', icon: 'el-icon-edit' },
  { label: '翻译助手', value: 'translate', icon: 'el-icon-connection' },
  { label: '数学助手', value: 'math', icon: 'el-icon-data-analysis' },
  { label: '知识问答', value: 'qa', icon: 'el-icon-question' },
  { label: 'AI编剧', value: 'scriptwriter', icon: 'el-icon-film' },
  { label: '语言阅读', value: 'reading', icon: 'el-icon-reading' }
];

const genres = [
  { label: '都市情感', value: 'urban' },
  { label: '悬疑推理', value: 'mystery' },
  { label: '古装武侠', value: 'wuxia' },
  { label: '科幻奇幻', value: 'scifi' },
  { label: '青春校园', value: 'youth' },
  { label: '家庭伦理', value: 'family' },
  { label: '职场商战', value: 'business' },
  { label: '历史传记', value: 'history' }
];

const scriptForm = ref({
  genre: '',
  plotPoints: '',
  characters: '',
  requirements: ''
});

const currentApp = ref('chat');
const inputText = ref('');
const chatBody = ref(null);
const shouldAutoScroll = ref(true);
const { ws, sendMessage,agentModel, connected, messages, loading } = createAgentAi();

const currentAppPlaceholder = computed(() => {
  const app = aiApps.find(a => a.value === currentApp.value);
  return `请输入您的问题... (${app?.label || '通用对话'})`;
});

const scriptDialogVisible = ref(false);

// 修改语音相关状态
const isSpeaking = ref(false);
const isListening = ref(false);
const recognition = ref(null);
const speechSynthesis = ref(window.speechSynthesis);
const voices = ref([]);
const currentVoice = ref(null);
const speechRate = ref(1.0);
const speechPitch = ref(1.0);

// 添加模型选择相关
const modelOptions = ref([
  { value: 'ep-20250204163109-jw9ch', label: 'Doubao-1.5-pro-256k' },
  { value: 'ep-20250204162538-9cmb2', label: 'DeepSeek-R1' },
  { value: 'ep-20250204190620-9n94t', label: 'DeepSeek-V3' },
  { value: 'ep-20250219225638-x9wwt', label: 'DeepSeek-R1-32B' },
]);

const selectedModel = ref(modelOptions.value[0].value);

// 添加语音功能支持检测
const hasSpeechRecognition = ref(false);
const hasSpeechSynthesis = ref(false);

// 修改语音识别初始化
const initSpeechRecognition = () => {
  if ('webkitSpeechRecognition' in window) {
    hasSpeechRecognition.value = true;
    recognition.value = new webkitSpeechRecognition();
    recognition.value.continuous = false;
    recognition.value.interimResults = true;
    recognition.value.lang = 'zh-CN';

    recognition.value.onstart = () => {
      isListening.value = true;
      ElMessage.info('开始录音，请说话...');
    };

    recognition.value.onresult = (event) => {
      const results = event.results;
      const lastResult = results[results.length - 1];
      const transcript = lastResult[0].transcript;
      
      if (lastResult.isFinal) {
        inputText.value = transcript;
        isListening.value = false;
        ElMessage.success('录音完成');
        // 自动发送识别结果
        handleSend(transcript);
      } else {
        // 实时显示识别结果
        inputText.value = transcript;
      }
    };

    recognition.value.onerror = (event) => {
      console.error('语音识别错误:', event.error);
      isListening.value = false;
      ElMessage.error('语音识别出错，请重试');
    };

    recognition.value.onend = () => {
      isListening.value = false;
    };
  } else {
    hasSpeechRecognition.value = false;
    ElMessage.warning('您的浏览器不支持语音识别，请使用Chrome浏览器');
  }
};

// 修改语音合成初始化
const initSpeechSynthesis = () => {
  if ('speechSynthesis' in window) {
    hasSpeechSynthesis.value = true;
    
    const loadVoices = () => {
      voices.value = speechSynthesis.value.getVoices();
      // 优先选择中文语音
      currentVoice.value = voices.value.find(voice => 
        voice.lang.includes('zh') && voice.name.includes('Microsoft')
      ) || voices.value.find(voice => voice.lang.includes('zh')) || voices.value[0];
      
      if (!currentVoice.value) {
        ElMessage.warning('未找到合适的中文语音，将使用默认语音');
      }
    };
    
    if (speechSynthesis.value.onvoiceschanged !== undefined) {
      speechSynthesis.value.onvoiceschanged = loadVoices;
    }
    loadVoices();
  } else {
    hasSpeechSynthesis.value = false;
    ElMessage.warning('您的浏览器不支持语音合成');
  }
};

// 开始语音识别
const startListening = () => {
  if (recognition.value) {
    try {
      recognition.value.start();
    } catch (error) {
      console.error('启动语音识别失败:', error);
      ElMessage.error('启动语音识别失败，请重试');
    }
  } else {
    ElMessage.warning('您的浏览器不支持语音识别');
  }
};

// 停止语音识别
const stopListening = () => {
  if (recognition.value) {
    recognition.value.stop();
    isListening.value = false;
  }
};

// 修改朗读文本函数
const speakText = (text) => {
  if (!text) {
    ElMessage.warning('没有可朗读的文本');
    return;
  }

  if (isSpeaking.value) {
    speechSynthesis.value.cancel();
  }

  const utterance = new SpeechSynthesisUtterance(text);
  
  // 设置语音参数
  if (currentVoice.value) {
    utterance.voice = currentVoice.value;
  }
  utterance.rate = speechRate.value;
  utterance.pitch = speechPitch.value;
  utterance.lang = 'zh-CN';
  utterance.volume = 1.0; // 设置音量
  
  utterance.onstart = () => {
    isSpeaking.value = true;
    ElMessage.info('开始朗读');
  };
  
  utterance.onend = () => {
    isSpeaking.value = false;
    ElMessage.success('朗读完成');
  };

  utterance.onerror = (event) => {
    console.error('语音合成错误:', event);
    isSpeaking.value = false;
    ElMessage.error('朗读出错，请重试');
  };

  try {
    speechSynthesis.value.speak(utterance);
  } catch (error) {
    console.error('启动语音合成失败:', error);
    ElMessage.error('启动朗读失败，请重试');
  }
};

// 停止朗读
const stopSpeaking = () => {
  speechSynthesis.value.cancel();
  isSpeaking.value = false;
  ElMessage.info('已停止朗读');
};

// 调整语速
const adjustSpeechRate = (delta) => {
  speechRate.value = Math.max(0.5, Math.min(2.0, speechRate.value + delta));
  if (isSpeaking.value) {
    stopSpeaking();
    speakText(inputText.value);
  }
};

// 调整音调
const adjustSpeechPitch = (delta) => {
  speechPitch.value = Math.max(0.5, Math.min(2.0, speechPitch.value + delta));
  if (isSpeaking.value) {
    stopSpeaking();
    speakText(inputText.value);
  }
};

const generateScript = async () => {
  if (!scriptForm.value.genre || !scriptForm.value.plotPoints) {
    ElMessage.warning('请填写剧集类型和剧情要点');
    return;
  }

  const prompt = `任务：为电视节目创作剧本。编剧需依据给定的剧集类型与剧情要点，编写出丰富、全面且引人入胜的剧本。
剧集类型：
${scriptForm.value.genre}
剧情要点：
${scriptForm.value.plotPoints}
角色设定：
${scriptForm.value.characters}

特殊要求：
${scriptForm.value.requirements}

创作要求：
1. 明确角色设定，涵盖主要角色性格、外貌及背景。
2. 依据剧集类型营造相符氛围与风格，如喜剧突出幽默，悬疑剧注重紧张情节。
3. 围绕剧情要点构建剧情，具备起承转合，情节合理且吸睛。
4. 编写贴合角色性格、自然流畅且推动剧情的对话。
5. 精准描述场景切换，让观众清晰想象故事发生场景。

请在标签内完成完整剧本创作，内容应丰富详细，满足电视节目剧本专业标准。
`;

  messages.value.push({
    role: 'user',
    content: prompt,
    app: 'scriptwriter',
    model: selectedModel.value
  });

  await scrollToBottom();

  try {
    sendMessage(prompt, 'scriptwriter', selectedModel.value);
  } catch (error) {
    ElMessage.error('生成剧本失败，请重试');
  }
};

const renderMarkdown = (content) => {
  return md.render(content);
};

const handleScroll = () => {
  if (!chatBody.value) return;
  const { scrollTop, scrollHeight, clientHeight } = chatBody.value;
  shouldAutoScroll.value = scrollHeight - scrollTop - clientHeight < 100;
};

const scrollToBottom = async () => {
  if (!shouldAutoScroll.value) return;

  await nextTick();
  if (chatBody.value) {
    chatBody.value.scrollTop = chatBody.value.scrollHeight;
  }
};

const handleSend = async () => {
  if (!inputText.value.trim()) return;

  const userMessage = inputText.value.trim();
  messages.value.push({
    role: 'user',
    content: userMessage,
    app: currentApp.value,
    model: selectedModel.value
  });

  await scrollToBottom();

  try {
    sendMessage(userMessage, currentApp.value, selectedModel.value);
    inputText.value = '';
  } catch (error) {
    ElMessage.error('发送消息失败，请重试');
  }
};

// 监听消息变化
watch(messages, async () => {
  await scrollToBottom();
}, { deep: true });

// 监听加载状态变化
watch(loading, async (newVal) => {
  if (!newVal) {
    await scrollToBottom();
  }
});

// 监听应用切换
watch(currentApp, () => {
  messages.value = [];
  inputText.value = '';
});

const selectApp = (appValue) => {
  if (appValue === 'scriptwriter') {
    scriptDialogVisible.value = true;
  } else {
    currentApp.value = appValue;
  }
};

const closeScriptDialog = () => {
  scriptDialogVisible.value = false;
  scriptForm.value = {
    genre: '',
    plotPoints: '',
    characters: '',
    requirements: ''
  };
};

const backToApps = () => {
  currentApp.value = '';
  messages.value = [];
  inputText.value = '';
};

// 在组件挂载时初始化语音功能
onMounted(() => {
  scrollToBottom();
  initSpeechRecognition();
  initSpeechSynthesis();
});

// 在组件卸载时清理
onUnmounted(() => {
  if (recognition.value) {
    recognition.value.stop();
  }
  if (speechSynthesis.value) {
    speechSynthesis.value.cancel();
  }
});

// 修改消息渲染函数
const renderMessage = (message) => {
  const content = renderMarkdown(message.content);
  return `
    <div class="message-wrapper">
      ${content}
      <div class="message-actions">
        <el-tooltip
          content="${isSpeaking.value ? '停止朗读' : '朗读文本'}"
          placement="top"
          :show-after="500"
        >
          <el-button 
            type="text" 
            size="small" 
            @click="speakText('${message.content.replace(/'/g, "\\'")}')"
            :class="{ 'is-speaking': isSpeaking }"
          >
            <i class="el-icon-video-play"></i>
          </el-button>
        </el-tooltip>
      </div>
    </div>
  `;
};
</script>

<style scoped>
.chat-page {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.chat-container {
  width: 1200px;
  height: 80vh;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  overflow: hidden;
}

/* 左侧应用列表样式 */
.apps-sidebar {
  width: 240px;
  background: #f8f9fa;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.connection-status {
  font-size: 14px;
  color: #999;
}

.connection-status.connected {
  color: #67C23A;
}

.apps-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  border-bottom: 1px solid #eee;
}

.app-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 8px;
}

.app-item:hover {
  background: #ecf5ff;
}

.app-item.active {
  background: #ecf5ff;
  color: #409EFF;
}

.app-icon {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #ecf5ff;
  color: #409EFF;
  display: flex;
  align-items: center;
  justify-content: center;
}

.app-icon i {
  font-size: 18px;
}

.app-name {
  font-size: 14px;
  font-weight: 500;
}

/* 右侧内容区域样式 */
.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.current-app-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.chat-body {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.chat-messages {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.chat-message {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.chat-message.user {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 8px;
  background: #f4f4f5;
  font-size: 14px;
  line-height: 1.5;
}

.user .message-content {
  background: #ecf5ff;
}

.chat-input {
  padding: 16px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 12px;
}

.chat-input .el-input {
  flex: 1;
}

.chat-actions {
  display: flex;
  gap: 12px;
  align-self: flex-end;
}

.reasoning-message {
  display: flex;
  gap: 12px;
  margin-left: 52px;
  margin-bottom: 8px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 8px;
  font-size: 13px;
  color: #666;
}

.reasoning-icon {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #e6f3ff;
  color: #409EFF;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.reasoning-content {
  flex: 1;
  line-height: 1.5;
}

.reasoning-content :deep(p) {
  margin: 0;
  padding: 0;
}

.reasoning-content :deep(pre) {
  background: #fff;
  padding: 8px;
  border-radius: 4px;
  overflow-x: auto;
  margin: 4px 0;
  border: 1px solid #eee;
}

.reasoning-content :deep(code) {
  font-family: 'Courier New', Courier, monospace;
  font-size: 12px;
}

.reasoning-content :deep(ul), .reasoning-content :deep(ol) {
  margin: 4px 0;
  padding-left: 16px;
}

.reasoning-content :deep(blockquote) {
  margin: 4px 0;
  padding-left: 8px;
  border-left: 3px solid #ddd;
  color: #666;
}

.reasoning-content :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 4px 0;
  font-size: 12px;
}

.reasoning-content :deep(th), .reasoning-content :deep(td) {
  border: 1px solid #eee;
  padding: 4px 8px;
  text-align: left;
}

.reasoning-content :deep(th) {
  background-color: #fff;
}

.genre-selector {
  width: 100%;
}

.scriptwriter-form :deep(.el-form-item__label) {
  font-weight: bold;
}

.scriptwriter-form :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.scriptwriter-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff inset;
}

.scriptwriter-form :deep(.el-textarea__inner) {
  font-family: 'Courier New', Courier, monospace;
  line-height: 1.6;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.message-wrapper {
  position: relative;
}

.message-actions {
  position: absolute;
  right: 8px;
  bottom: 8px;
  opacity: 0;
  transition: opacity 0.3s;
  display: flex;
  gap: 4px;
  background: rgba(255, 255, 255, 0.9);
  padding: 4px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-wrapper:hover .message-actions {
  opacity: 1;
}

.message-actions .el-button {
  padding: 4px 8px;
  height: 24px;
  width: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.message-actions .el-button i {
  font-size: 16px;
}

.is-speaking {
  color: #409EFF;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

/* 模型选择器样式 */
.model-selector {
  padding: 16px;
  border-top: 1px solid #eee;
  background: #fff;
}

.selector-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

.model-select {
  width: 100%;
}

.model-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.model-option i {
  font-size: 16px;
  color: #409EFF;
}

/* 修改语音按钮样式 */
.is-listening {
  animation: pulse 1.5s infinite;
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.is-listening:hover {
  background-color: #f78989;
  border-color: #f78989;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}
</style>
